const { v4: uuidv4 } = require('uuid');
import { URL } from 'url';

class common {
    public get uuid(): string {
        return uuidv4().replace(/-/g, '')
    }

    // 生成指定范围的随机数
    random(min: number, max: number): number {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    constructor() {

    }
    /**
     * 解析指令 指令格式 (内容数字a数字)
     * 内容解析
    * 预期指令: 使用数字
    * 如使用0 使用1 使用2 使用3
    * 如使用0q1 使用1q2 使用2q3 使用3q4
     */
    cover_number(data: string) {
        let indexMatch = data.match(/\d+/);
        let index = indexMatch ? parseInt(indexMatch[0], 10) : null;
        let indexMatch2 = data.match(/\d+q\d+/);
        let index2 = indexMatch2 ? parseInt(indexMatch2[0].split('q')[1], 10) : null;
        return { k1: Math.ceil(index || 0), k2: Math.ceil(index2 || 0) };
    }
    /**
     * 随机权重
     * @param data 
     * @returns 
     */
    randomWeight(data: { min: number; max: number }) {
        data = { min: Number(data.min), max: Number(data.max) };
        const range = data.max - data.min + 1;
        const weights = Array.from({ length: range }, (_, i) => range - i);
        const totalWeight = weights.reduce((acc, weight) => acc + weight, 0);
        let random = Math.random() * totalWeight;
        let chosenNumber = data.min;
        for (let i = 0; i < weights.length; i++) {
            random -= weights[i];
            if (random <= 0) {
                chosenNumber = data.min + i;
                break;
            }
        }
        const probabilities = weights.map(weight => (weight / totalWeight) * 100);
        probabilities.forEach((probability, index) => {
            console.log(`Number ${data.min + index}: ${probability.toFixed(2)}%`);
        });
        return chosenNumber;
    }
    /**
     * 格式化数字 如果数字小于10 则前面补0
     * @param num 
     * @returns 
     */
    formatNumberWithLeadingZero(num: number): string {
        let numStr = num.toString();
        if (!numStr.startsWith('0')) {
            numStr = '0' + numStr;
        }
        return numStr;
    }
    // 倒计时
    countDown(time: number) {
        let now = Date.now();
        let diff = Math.floor((time - now) / 1000);
        return diff;
    }
    getCfgAttributeVal(data: any, key: string): number {
        let val = 0;
        if (!data) {
            return val;
        }
        if (data instanceof Array) {
            val = data.find((item: any) => item.key == key)?.val || 0;
        } else {
            val = data.key == key ? data.val : 0;
        }

        return Number(val);
    }
    /**
     * 时间戳转为年月日时分秒
     */
    timestampToTime(timestamp: number): string {
        const date = new Date(timestamp);
        return date.toLocaleString();
    }
}
export default new common();

/**
 * 从腾讯云COS删除图片
 * @param imageUrl 图片URL
 * @returns 是否删除成功
 */
export async function deleteImageFromCOS(imageUrl: string): Promise<boolean> {
    try {
        // 解析图片URL，提取文件路径
        const url = new URL(imageUrl);
        const pathParts = url.pathname.split('/');
        const fileName = pathParts[pathParts.length - 1];
        
        // 如果没有文件名，返回失败
        if (!fileName) {
            console.error('无法从URL中提取文件名:', imageUrl);
            return false;
        }

        const COS = require('cos-nodejs-sdk-v5');
        const cos = new COS({
            SecretId: process.env.COS_SECRET_ID,
            SecretKey: process.env.COS_SECRET_KEY,
        });

        // 删除COS中的文件
        await cos.deleteObject({
            Bucket: "dew-1251587647",
            Region: "ap-guangzhou",
            Key: `upload/${fileName}`
        });

        console.log(`腾讯云图片删除成功: ${fileName}`);
        return true;
    } catch (error) {
        console.error('删除腾讯云图片失败:', error);
        return false;
    }
}